import { defineStore } from 'pinia'
import { getUserList, createUser, updateUser, deleteUser, batchDeleteUsers, resetUserPassword, updateUserStatus } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    userList: [],
    total: 0,
    loading: false,
    currentUser: null
  }),

  actions: {
    async fetchUserList(params) {
      this.loading = true
      try {
        const response = await getUserList(params)
        this.userList = response.data.records || []
        this.total = response.data.total || 0
        return response.data
      } catch (error) {
        throw error
      } finally {
        this.loading = false
      }
    },

    async createUser(data) {
      try {
        return await createUser(data)
      } catch (error) {
        throw error
      }
    },

    async updateUser(id, data) {
      try {
        return await updateUser(id, data)
      } catch (error) {
        throw error
      }
    },

    async deleteUser(id) {
      try {
        return await deleteUser(id)
      } catch (error) {
        throw error
      }
    },

    async batchDeleteUsers(ids) {
      try {
        return await batchDeleteUsers(ids)
      } catch (error) {
        throw error
      }
    },

    async resetUserPassword(id) {
      try {
        return await resetUserPassword(id)
      } catch (error) {
        throw error
      }
    },

    async updateUserStatus(id, status) {
      try {
        return await updateUserStatus(id, status)
      } catch (error) {
        throw error
      }
    },

    setCurrentUser(user) {
      this.currentUser = user
    }
  }
})